/*
 * @lc app=leetcode.cn id=23 lang=golang
 *
 * [23] 合并 K 个升序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeKLists(lists []*ListNode) *ListNode {
	minSearchNode := func() *ListNode {
		min := &ListNode{Val: math.MaxInt32}
		index := -1
		for i, list := range lists {
			if list == nil {
				continue
			}
			if list.Val < min.Val {
				min = list
				index = i
			}
		}
		if index == -1 {
			return nil
		}
		lists[index] = min.Next
		return min
	}
	ans := &ListNode{}
	ptr := ans
	minNode := ans
	for minNode != nil {
		minNode = minSearchNode()
		ptr.Next = minNode
		ptr = ptr.Next

	}
	return ans.Next
}

// @lc code=end

